from rest_framework import serializers
from .models import Article,ArticleGroup,Mission, Encyclopedia, EncyclopediaGroup, EncyclopediaSection, EncyclopediaSectionItem, LaunchSite, Institution, InstitutionRelation, KnowledgeQuestion

class MissionSerializer(serializers.ModelSerializer):
    missionName = serializers.CharField(source='mission_name')
    imageUrl = serializers.URLField(source='image_url')
    headerImage = serializers.URLField(source='header_image')
    launchTime = serializers.CharField(source='launch_time')
    launchTimeUTC = serializers.DateTimeField(source='launch_time_utc', format='%Y-%m-%dT%H:%M:%SZ')
    isDisplayable = serializers.BooleanField(source='is_displayable')
    isCountable = serializers.BooleanField(source='is_countable')

    class Meta:
        model = Mission
        fields = ['id', 'institution', 'missionName', 'launchTime', 'imageUrl', "headerImage",'status', 'launchTimeUTC', 'isDisplayable', 'isCountable']

class EncyclopediaSerializer(serializers.ModelSerializer):
    iconUrl = serializers.CharField(source='icon_url')
    coverUrl = serializers.CharField(source='cover_url')
    
    class Meta:
        model = Encyclopedia
        fields = ['id', 'type', 'name', 'alias', 'url', 'tags', 'iconUrl', 'coverUrl', 'content', 'scaletype', 'colorfield']

# 百科词条关联序列化器 - 移到前面
class EncyclopediaSectionItemSerializer(serializers.ModelSerializer):
    encyclopedia = EncyclopediaSerializer(read_only=True)
    
    class Meta:
        model = EncyclopediaSectionItem
        fields = ['id', 'encyclopedia', 'order']

# 百科内容组子部分序列化器 - 移到前面
class EncyclopediaSectionSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()
    itemsCount = serializers.SerializerMethodField()
    
    class Meta:
        model = EncyclopediaSection
        fields = ['id', 'subtitle', 'order', 'items', 'itemsCount']
        
    def get_items(self, obj):
        # 直接返回词条对象，按order排序
        section_items = obj.items.select_related('encyclopedia').order_by('order')
        return [EncyclopediaSerializer(item.encyclopedia).data for item in section_items]
        
    def get_itemsCount(self, obj):
        return obj.items.count()

# 百科内容组序列化器 - 移到最后
class EncyclopediaGroupSerializer(serializers.ModelSerializer):
    sections = EncyclopediaSectionSerializer(many=True, read_only=True)
    sectionsCount = serializers.SerializerMethodField()
    totalItemsCount = serializers.SerializerMethodField()
    
    class Meta:
        model = EncyclopediaGroup
        fields = ['id', 'title', 'description', 'sections', 'sectionsCount', 'totalItemsCount']
        
    def get_sectionsCount(self, obj):
        return obj.sections.count()
        
    def get_totalItemsCount(self, obj):
        return sum(section.items.count() for section in obj.sections.all())

# 先定义 InstitutionSerializer（不包含 related_institutions）
class InstitutionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Institution
        fields = ['id', 'name', 'logo', 'country', 'nature', 'image_url', 'basic_info', 'content', 'order']

# 然后定义 InstitutionRelationSerializer
class InstitutionRelationSerializer(serializers.ModelSerializer):
    institution = InstitutionSerializer(source='to_institution', read_only=True)
    
    class Meta:
        model = InstitutionRelation
        fields = ['role', 'institution', 'order']

# 最后定义包含相关机构的完整 InstitutionSerializer
class InstitutionWithRelationsSerializer(serializers.ModelSerializer):
    related_institutions = serializers.SerializerMethodField()
    
    class Meta:
        model = Institution
        fields = ['id', 'name', 'logo', 'country', 'nature', 'image_url', 'basic_info', 'content', 'order', 'related_institutions']
    
    def get_related_institutions(self, obj):
        relations = InstitutionRelation.objects.filter(from_institution=obj).order_by('order')
        return InstitutionRelationSerializer(relations, many=True).data

class LaunchSiteSerializer(serializers.ModelSerializer):
    active_pads = serializers.IntegerField(source='active_pads')
    latitude_type = serializers.CharField(source='latitude_type')
    location_type = serializers.CharField(source='location_type')
    image_url = serializers.CharField(source='image_url')
    basic_info = serializers.JSONField(source='basic_info')
    annual_launches = serializers.SerializerMethodField()

    class Meta:
        model = LaunchSite
        fields = ['id', 'name', 'location', 'active_pads', 'latitude_type', 'location_type', 'image_url', 'basic_info', 'annual_launches']

    def get_annual_launches(self, obj):
        # 由于模型中没有 annual_launches 字段，返回默认值 0
        # 如果需要实际数据，需要在模型中添加此字段或通过其他方式计算
        return 0


class KnowledgeQuestionSerializer(serializers.ModelSerializer):
    """知识题库序列化器"""
    
    class Meta:
        model = KnowledgeQuestion
        fields = ['id', 'question', 'option_a', 'option_b', 'option_c', 'option_d', 'correct_answer', 'explanation']


# 文章序列化器
class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title', 'type', 'url', 'column', 'date', 'image_url']


# 替换现有的ArticleGroupSerializer实现

class ArticleGroupSerializer(serializers.ModelSerializer):
    articles = serializers.SerializerMethodField()
    articles_count = serializers.SerializerMethodField()
    
    class Meta:
        model = ArticleGroup
        fields = ['id', 'title', 'description', 'articles', 'articles_count']
        
    def get_articles(self, obj):
        # 获取关联的文章，按日期从新到旧排序
        articles = obj.articles.all().order_by('-date')
        return ArticleSerializer(articles, many=True).data
        
    def get_articles_count(self, obj):
        return obj.articles.count()


